/*
 * BAT_Writer.c
 *
 * An output class for any format from a BAT.
 *
 * Bob Zimmermann <rpz@cse.wustl.edu> Totally free.
 */

#include "BAT_Writer.h"
#include "BAT_Factory.h"

BAT_Writer *
BAT_Writer_new()
{
  BAT_Writer *w;
  w = malloc(sizeof(BAT_Writer));
  return w;
}

void
BAT_Writer_delete(BAT_Writer * w, int befrei)
{
  if (befrei)
    free(w);
}

void
BAT_Writer_write_file(BAT_Writer * w, char *filename, BAT_Writer_Type wt,
		      void *o, BAT_Object_Type t)
{
  BAT_Factory *fac;
  BAT_Write_Plugin *wh;
  char *fullname;
  FILE *f;

  fac = BAT_Factory_new();
  wh = BAT_Factory_get_write_plugin(fac, wt);
  fullname = malloc((strlen(filename) + 1 + BAT_WRITER_EXT_LEN) * sizeof(char));
  strcpy(fullname, filename);
  strcat(fullname, wh->ext);

  f = fopen(fullname, "w");
  if (f == NULL) {
    fprintf(stderr, "Could not open %s for writing.", fullname);
    exit(1);
  }
  BAT_Writer_write_to_fh(w, f, wt, o, t);

  BAT_Factory_delete(fac, 1);
  free(fullname);
}

void
BAT_Writer_write_to_fh(BAT_Writer * w, FILE * fh, BAT_Writer_Type wt, void *o,
		       BAT_Object_Type t)
{
  BAT_Factory *fac;
  BAT_Write_Plugin *wh;
  void *wc;

  fac = BAT_Factory_new();
  wh = BAT_Factory_get_write_plugin(fac, wt);
  wc = wh->construct();

  switch (t) {
  case BAT_GTF_Obj:
    wh->write_gene_table(wc, fh, (BAT_GeneTab *) o);
    break;
  case BAT_Gene_Obj:
    wh->write_gene(wc, fh, (BAT_Gene *) o);
    break;
  case BAT_Transcript_Obj:
    wh->write_transcript(wc, fh, (BAT_Transcript *) o);
    break;
  case BAT_Feature_Obj:
    wh->write_feature(wc, fh, (BAT_Feature *) o);
    break;
  case BAT_Free_Feature_Obj:
    wh->write_feature(wc, fh, (BAT_Feature *) o);
    break;
  case BAT_Attribute_Obj:
    wh->write_attribute(wc, fh, (BAT_Attribute *) o);
    break;
  }

  wh->delete(wc, 1);
  BAT_Factory_delete(fac, 1);
}
